package com.attendancesystem.controller;

import com.attendancesystem.service.LectureService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;



import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.sql.*;
import java.util.List;

@WebServlet(name = "BatchDeleteLecturesController", value = "/BatchDeleteLecturesController")
public class BatchDeleteLecturesController extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
   protected void doDelete(HttpServletRequest req, HttpServletResponse rep) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        rep.setContentType("application/json;charset=UTF-8");
        try {
            // 1. 解析请求体中的JSON数据
            List<Integer> ids = objectMapper.readValue(
                    req.getReader(),
                    objectMapper.getTypeFactory().constructCollectionType(List.class, Integer.class)
            );
            LectureService lectureService = new LectureService();
            boolean success = false;
            for (Integer id : ids){
                if (lectureService.BatchDeleteLectures(id))
                {
                    success = true;
//                    System.out.println("id:"+id);
                }


            }
//            System.out.println("ids:"+ids);

            // 2. 验证数据有效性
            if (ids == null || ids.isEmpty()) {
                sendErrorResponse(rep, 400, "无效的请求参数");
                return;
            }

            // 3. 执行批量删除操作（示例）


            // 4. 返回操作结果
            if (success) {
                rep.getWriter().write(
                        objectMapper.writeValueAsString(
                                new Result(true, "成功删除 " + ids.size() + " 条记录")
                        )
                );
            } else {
                sendErrorResponse(rep, 500, "部分或全部删除操作失败");
            }
        } catch (Exception e) {
            sendErrorResponse(rep, 500, "服务器处理错误: " + e.getMessage());
        }

    }
    private void sendErrorResponse(HttpServletResponse resp, int code, String msg)
            throws IOException {
        resp.setStatus(code);
        resp.getWriter().write(
                objectMapper.writeValueAsString(new Result(false, msg))
        );
    }

    // 简单结果类
    private static class Result {
        public boolean success;
        public String message;

        public Result(boolean success, String message) {
            this.success = success;
            this.message = message;
        }
    }
}
